import { Button, Form, Input, Toast } from "antd-mobile";
import axios from "axios";
import { useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useSearchParams } from "react-router-dom";
import { loginSuccess } from "../../store/user";
import { withPerformance } from "../withPerformance";
const TelLoginComp = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch()
  const [searchParams] = useSearchParams()
  const from = searchParams.get("from") || "/"
  // 提交表单
  const onFinish = async (values) => {
    const resp = await axios.post("/api/login/tel", values);
    const { code, message, data } = resp.data;

    if (code === 200) {
      Toast.show(message);

      dispatch(loginSuccess(data))
      
      navigate(from, { replace: true });
    } else {
      Toast.show(message);
    }
  };
  // 获取验证码
  const getCode = () => {
    // 需要知道 手机号是否验证通过
    // 通过获取 form 实例， 调用 validateFields 方法  来验证手机号
    form.current
      .validateFields(["tel"])
      .then((resp) => {
        // 发送请求 获取验证码
        getCodeApi();
      })
      .catch((error) => {
        console.log("error", error);
      });
  };

  const getCodeApi = async () => {
    const tel = form.current.getFieldValue("tel");

    const resp = await axios.get("/api/login/code", { params: { tel } });

    const { code, message } = resp.data;

    if (code === 200) {
      // 开始倒计时
      const timer = setInterval(() => {
        setCurtDownCount((prev) => {
          const nextPrev = prev - 1;
          if (nextPrev <= 0) {
            clearInterval(timer);
            return curtCount;
          }
          return nextPrev;
        });
      }, 1000);
      Toast.show(message);
    } else {
      Toast.show(message);
    }
  };
  // form 实例
  const form = useRef();
  const curtCount = 60;
  const [curtDownCount, setCurtDownCount] = useState(curtCount);

  return (
    <div>
      <Form
        ref={form}
        onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button block color="primary" type="submit">
            立即登录
          </Button>
        }
      >
        <Form.Item
          name="tel"
          label="手机号"
          rules={[
            {
              required: true,
              message: "请输入手机号",
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入正确的手机号",
            },
          ]}
        >
          <Input placeholder="请输入手机号"></Input>
        </Form.Item>
        <Form.Item
          name="telCode"
          label="验证码"
          extra={
            <Button
              disabled={curtDownCount !== curtCount}
              onClick={() => getCode()}
            >
              {curtDownCount === curtCount
                ? "获取验证码"
                : `${curtDownCount}s后重新获取`}
            </Button>
          }
          rules={[
            {
              required: true,
              message: "请输入验证码",
            },
          ]}
        >
          <Input placeholder="请输入手机号"></Input>
        </Form.Item>
      </Form>
    </div>
  );
};

export default withPerformance(TelLoginComp);
